package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.TailorAdapter;
import flc.ast.bean.TailorBean;
import flc.ast.databinding.ActivityVideoTailorBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.CutView;

public class VideoTailorActivity extends BaseAc<ActivityVideoTailorBinding> implements MediaPlayer.OnPreparedListener {

    public static String videoPath,savePath;
    private TailorAdapter tailorAdapter;
    protected int mVideoOriWidth = -1;
    protected int mVideoOriHeight = -1;
    private int oldPosition=0;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoSbLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };
    @Override
    protected int onCreate() {
        return R.layout.activity_video_tailor;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoTailorBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivGenerate.setOnClickListener(this);
        mDataBinding.tvDeriveVideo.setOnClickListener(this);
        mDataBinding.videoView.setOnPreparedListener(this);
        mDataBinding.rvVideoTailorList.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
        tailorAdapter=new TailorAdapter();
        mDataBinding.rvVideoTailorList.setAdapter(tailorAdapter);
        tailorAdapter.setOnItemClickListener(this);
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                mDataBinding.cutView.setMargin(mDataBinding.videoView.getLeft(), mDataBinding.videoView.getTop(),
                        mDataBinding.videoView.getRight() - mDataBinding.videoView.getWidth(), mDataBinding.videoView.getBottom() - mDataBinding.videoView.getHeight());
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivGenerate:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                tailorVideo();
                break;
            case R.id.tvDeriveVideo:
                saveVideo();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        tailorAdapter.getItem(oldPosition).setSelect(false);
        tailorAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        tailorAdapter.getItem(position).setSelect(true);
        tailorAdapter.notifyItemChanged(position);
        setView(position);
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        savePath=videoPath;
        //设置播放器
        setPlayer();
        //裁剪数据
        List<TailorBean> listCut = new ArrayList<>();
        listCut.add(new TailorBean("原图", R.drawable.yuantu1, -1f, true));
        listCut.add(new TailorBean("1:1", R.drawable.t11, 1f, false));
        listCut.add(new TailorBean("1:2", R.drawable.t12, 1f / 2f, false));
        listCut.add(new TailorBean("1:3", R.drawable.t13, 1f / 3f, false));
        listCut.add(new TailorBean("2:3", R.drawable.t23, 2f / 3f, false));
        listCut.add(new TailorBean("3:4", R.drawable.t34, 3f / 4f, false));
        tailorAdapter.setList(listCut);
    }

    //临时保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到相册
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, savePath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        },500);
                    }
                });
            }
        }, 1000);
    }

    //设置裁剪框
    private void setView(int position) {
        //计算一下
        int left = mDataBinding.videoView.getLeft();
        int right = mDataBinding.videoView.getRight() - mDataBinding.videoView.getWidth();
        int top = mDataBinding.videoView.getTop();
        int bottom = mDataBinding.videoView.getBottom() - mDataBinding.videoView.getHeight();
        switch (position) {
            case 0://原图
                break;
            case 1://1:1
                left = 100;
                top = 100;
                right = 100;
                bottom = 100;
                break;
            case 2://1:2
                left = 200;
                top = 100;
                right = 200;
                bottom = 100;
                break;
            case 3://1:3
                left = 300;
                top = 100;
                right = 300;
                bottom = 100;
                break;
            case 4://2:3
                left = 150;
                top = 100;
                right = 150;
                bottom = 100;
                break;
            case 5://3:4
                left = 120;
                top = 100;
                right = 120;
                bottom = 100;
                break;
        }
        mDataBinding.cutView.setMargin(left, top, right, bottom);
    }

    //剪切视频
    private void tailorVideo() {
        Rect rect = getCropValueInfo();
        EditorHolder.editor().videoCrop(videoPath, rect.right, rect.bottom,
                rect.left, rect.top, new IEditorListener() {
                    @Override
                    public void onSuccess(String outFilePath) {
                        dismissDialog();
                        savePath = outFilePath;
                        mDataBinding.videoView.setVideoPath(outFilePath);
                        mDataBinding.videoView.seekTo(1);
                        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                        mDataBinding.videoView.start();
                        startTime();
                    }

                    @Override
                    public void onFailure(String errMsg) {
                        dismissDialog();
                        Log.e("TAG", "onFailure: "+errMsg );
                        ToastUtils.showShort(R.string.tailor_def);
                    }

                    @Override
                    public void onProgress(int progress) {
                        showDialog(getString(R.string.tailor_ing) + progress + "%");
                    }
                });
    }

    private Rect getCropValueInfo() {
        CutView cutView = mDataBinding.cutView;
        float[] cutArr = cutView.getCutArr();
        float left = cutArr[0];
        float top = cutArr[1];
        float right = cutArr[2];
        float bottom = cutArr[3];
        int cutWidth = cutView.getRectWidth();
        int cutHeight = cutView.getRectHeight();

        //计算宽高缩放比
        float leftPro = left / cutWidth;
        float topPro = top / cutHeight;
        float rightPro = right / cutWidth;
        float bottomPro = bottom / cutHeight;

        //得到裁剪位置
        int cropWidth = (int) (mVideoOriWidth * (rightPro - leftPro));
        int cropHeight = (int) (mVideoOriHeight * (bottomPro - topPro));
        int x = (int) (leftPro * mVideoOriWidth);
        int y = (int) (topPro * mVideoOriHeight);

        return new Rect(x, y, cropWidth, cropHeight);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvVideoSbLeft.setText("00:00");
        mDataBinding.tvVideoSbRight.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoSbLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
        mDataBinding.videoView.start();
        startTime();
        stopTime();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mVideoOriWidth = mp.getVideoWidth();
        mVideoOriHeight = mp.getVideoHeight();

    }
}